package com.md.common.utils.web.auth;


import org.apache.commons.codec.binary.Base64;

import java.nio.ByteBuffer;

/**
 * 功能描述：base64编码工具
 *
 * @author lujianping@oak168.com
 * @version 1.0
 * @date 2018-7-16 10:46
 * @since JDK 1.8
 */
public class BaseCodeUtil {
    public static String encodeBytesBase64(byte[] bytes) {
        return new String(Base64.encodeBase64(bytes));
    }

    public static String encodeIntBase64(int value) {
        byte[] bytes = ByteBuffer.allocate(4).putInt(0, value).array();
        return encodeBytesBase64(bytes);
    }

    public static String encodeLongBase64(long value) {
        byte[] bytes = ByteBuffer.allocate(8).putLong(0, value).array();
        return encodeBytesBase64(bytes);
    }

    public static String encodeFloatBase64(float value) {
        byte[] bytes = ByteBuffer.allocate(4).putFloat(0, value).array();
        return encodeBytesBase64(bytes);
    }

    public static String encodeDoubleBase64(double value) {
        byte[] bytes = ByteBuffer.allocate(8).putDouble(0, value).array();
        return encodeBytesBase64(bytes);
    }

    public static String encodeStringBase64(String value) {
        return encodeBytesBase64(value.getBytes());
    }

    public static byte[] decodeBytesBase64(String value) {
        return Base64.decodeBase64(value.getBytes());
    }

    public static int decodeIntBase64(String value) {
        byte[] bytes = Base64.decodeBase64(value.getBytes());
        ByteBuffer byteBuffer = ByteBuffer.allocate(4).put(bytes, 0, bytes.length);
        byteBuffer.flip();
        return byteBuffer.getInt();
    }

    public static long decodeLongBase64(String value) {
        byte[] bytes = Base64.decodeBase64(value.getBytes());
        ByteBuffer byteBuffer = ByteBuffer.allocate(8).put(bytes, 0, bytes.length);
        byteBuffer.flip();
        return byteBuffer.getLong();
    }

    public static float decodeFloatBase64(String value) {
        byte[] bytes = Base64.decodeBase64(value.getBytes());
        ByteBuffer byteBuffer = ByteBuffer.allocate(4).put(bytes, 0, bytes.length);
        byteBuffer.flip();
        return byteBuffer.getFloat();
    }

    public static double decodeDoubleBase64(String value) {
        byte[] bytes = Base64.decodeBase64(value.getBytes());
        ByteBuffer byteBuffer = ByteBuffer.allocate(8).put(bytes, 0, bytes.length);
        byteBuffer.flip();
        return byteBuffer.getDouble();
    }

    public static String decodeStringBase64(String value) {
        return new String(Base64.decodeBase64(value.getBytes()));
    }
}
